package com.pandarouter;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;



public class Worker {
	public static boolean webEnable = false;
	public static boolean sshEnable = false;
	public static String remoteUrl = "";
	public static String localUrl = "";
	public static String ssh_remoteUrl = "";
	public static String sshHost = "";
	public static int sshPort = 22;
	public static String sshUser = "";
	public static String sshPwd = "";
	public static int threadsNum = 0;
	public static int totalAllowedThreadsNum = 5;
	public static boolean isActive = false;
	public static int activeTime = 20; // seconds
	public static long lastActived;
	private Runnable req,ssh;
	public static void main(String[] args){
		//
		//String r = SSH.exec("127.0.0.1", "root", "pandaplot", 23, "cd /home");
		//System.out.println(r);
		init();
		new Worker();
	}
	/**
	 * load configuration file
	 */
	private static void init(){
		Properties props = new Properties();
		InputStream in;
		try{
			in = Worker.class.getResourceAsStream("/config.properties");
			if(in != null){
				props.load(in);
				in.close();
			}else
				throw new FileNotFoundException("config.properties not found... exit.");
			webEnable = props.getProperty("web").equals("1")?true:false;
			sshEnable = props.getProperty("ssh").equals("1")?true:false;
			remoteUrl = props.getProperty("web_remoteUrl");
			ssh_remoteUrl = props.getProperty("ssh_remoteUrl");
			localUrl = props.getProperty("web_localUrl");
			sshHost = props.getProperty("ssh_host");
			sshPort = Integer.valueOf(props.getProperty("ssh_port"));
			sshUser = props.getProperty("ssh_user");
			sshPwd = props.getProperty("ssh_pwd");
		}catch(FileNotFoundException e){
			e.printStackTrace();
			System.exit(0);
		}catch(Exception e) {
			e.printStackTrace();
			System.out.println("error while parsing config.properties");
		}
	}
	Worker(){
		req=new Req();
		ssh=new SSH();
		// ssh monitor single thread
		Thread ssh1;
		if(sshEnable) {
			ssh1=new Thread(ssh);
			ssh1.start();
		}
		Monitor();
	}
	public void Monitor(){
		Thread th1;
		try{
			// web monitor
			while(webEnable) {
				if((System.currentTimeMillis() - lastActived)>activeTime*1000)
					isActive = false;
				if(totalAllowedThreadsNum>threadsNum && isActive) {
					th1=new Thread(req);
					th1.start();
					Thread.sleep(200);
				}else if(totalAllowedThreadsNum<=threadsNum){
					Thread.sleep(500);
				}else {
					th1=new Thread(req);
					th1.start();
					Thread.sleep(2000);
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	public static void echo(String str){
		System.out.println(str);
	}
}

